<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/11/9
 * Time: 16:36
 */

namespace app\api\controller;


use think\Db;

class Ali extends Common
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAudTP/Y73OrKTNdMiCmpKIr5GNsZmZPGv0MPMNtqxMzXX+xR53TpUA/ZGTduvVqf8huLm2r3ftQUy/XRyo3UBxkZWmgFdfARXbYOjeDwy9GQR2r8FhLk+zOP6ZbSqopmlU3kKI+zY7xtXXJvomIb7RmSNE2+njMljqYl/S5RxZW1LiZAeP0is2NE47twoEyTAtdpdEAgI7HZi6MLMkqvdBa0ff0F5COwr8599A61RLqXe6kQeQOBqeo/7dk9nBjWaTZlXe5aJ/yVBFwHZBBilZkJkXhwzi9r8J5QHVw4+Wmf5e6Qbb1iKjLxujVtZ0R6sa5PTGedB2+vvbMQTT5DJOQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA02wBz1kMREnLuFbizJxIxLgPZ7f7H0sgNxjeeoh9k8X4qVtp3166ce7VCxU0FzCEVozBvPejdNeVqpbI+NlLpHvpAJc88B/Uev29T8nZTEqxTuPdoqY1a9ENHH4Z1e1zHG75Ok9keNOtwlS5OWfTNTtUifbJe6F0qR7EUEUXNN8Y6o0RxBh6ecVwLmtQJ30RSV1rh2dfG/DUZoNdeS1AaqftE8rEpif6xu0uodpJ4rST7+BMOL02Cjh3IhuobCk2Sm3QBerSkK5Xgg7KlRsV8o/2WFhdGzKcOcTBjel2Svx9hMdL0gb0Xp4V+bFIWKx5gSEvTS78HLZ7LYKCBEg/xwIDAQAB",
        'private_key' => 'MIIEpQIBAAKCAQEA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752rOt+es8XJokD6UE2P/uQ93PiGOhesUsVGYNILAPH4XD0uILNECEZTUV4+IAJD8XjwPehthbJAuEhoxl7TxU1GSUZlWwn7NmyaJgkZ7fxR9Fxa8KjX/98S5rutNqRwLj5ZMpldLGBd32/dm9hUsg0CgYEArLO5qmcUc46KReoawHogIpY2oCk17F8B3kIGLmPFglnI/QopmR1ZPunZnS+yp9AWct64C+EZcsYO58iOZNFtu9q6HwQ+cXzjUh5wfRyUA/NPS+zpczKQWucjsJJtFi3uTxGkKwf4C2p337rz7Uz1MfpIQJRcF0MBKEhPv+JowckCgYEA5KBmh+UJsjCWkcthKaBkmqLCD2vWSN8unSzd4AL6ShWPnv54i3bESkzcAM5xFkjJNgC3PqWymy7sY2w3XYNqwclEbivZc6eekmjwlQWPl306GPTEnDpcR+mKP7OgwlT2AEPX4PjaRBxJ42As7cbKqr618pAutmtA76nKHNUmPAY='
    );
    
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//    public function getParam(){
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
//        $money = '0.01';
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2018082761111629";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://south.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    
    /**
     * 生成订单
     * @return string|void
     * order_id：订单ID
     */
    public function alipay()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
        }
        $orderInfo = Db::table('up_order')->where('o_id', $params['order_id'])->find();
        if($orderInfo) {
            $respont = $this->getParam($orderInfo['order_num'], $orderInfo['pay_price'], '酒店预订', '酒店预订');
            return json_encode($respont);
        } else {
            return json_encode(['status' => 0, 'data' => '订单错误']);
        }
    }
    
    /**
     * 回调
     * @return string
     */
    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $dataOrder = array();
//                $dataOrder['order_trade_no'] = $getInfo['trade_no'];//支付宝返回的支付宝生成的订单号
//                $dataOrder['order_boos_get'] = $getInfo['receipt_amount'];//商家实际收的金额
//                $dataOrder['order_user_pay'] = $getInfo['buyer_pay_amount'];//用户实付金额
//                $dataOrder['order_ali_fund_bill_list'] = $getInfo['fund_bill_list'];//支付宝支付信息
                $dataOrder['pay_time'] = $getInfo['gmt_payment'];//支付时间
                $dataOrder['order_status'] = 2;//订单状态  1未支付   2已支付
                Db::startTrans();
                try {
                    Db::table('up_order')->where('order_num', $num)->update($dataOrder);
                    Db::commit();
//                    $this->Jpush("{$change['order_user_id']}", '购买权限成功', 1, '');
                    die('success');
//                }
                } catch(\Exception $e) {
                    Db::rollback();
                    return 'error';
                }
            }
        }
    }
}